<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="订单编号" prop="appointmentNo">
        <el-input
            v-model="queryParams.appointmentNo"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
          <el-option label="全部" value="" />
          <el-option label="待确认" value="0" />
          <el-option label="已确认" value="1" />
          <el-option label="已完成" value="2" />
          <el-option label="已取消" value="3" />
          <el-option label="已过期" value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
            v-model="queryParams.patientName"
            placeholder="请输入患者姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="就诊日期">
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['record:detail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['record:detail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['record:detail:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['record:detail:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="appointmentNo" width="200" />
      <el-table-column label="挂号费用" align="center" prop="appointmentFee" width="100">
        <template #default="scope">
          <span>{{ scope.row.appointmentFee || '0.00' }}¥</span>
        </template>
      </el-table-column>
      <el-table-column label="就诊人" align="center" prop="patientName" width="120" />
      <el-table-column label="医院" align="center" prop="hospitalName" width="150" />
      <el-table-column label="科室" align="center" prop="departmentName" width="150" />
      <el-table-column label="医生" align="center" prop="doctorName" width="120" />
      <el-table-column label="下单时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="就诊日期" align="center" prop="visitTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.visitTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag
              :type="getStatusType(scope.row.status)"
              effect="plain"
          >
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['record:detail:query']">查看详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['record:detail:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['record:detail:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改预约对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="detailRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="预约排班" prop="scheduleId">
              <el-select
                  v-model="form.scheduleId"
                  placeholder="请选择预约排班"
                  clearable
                  filterable
                  @change="handleScheduleChange"
              >
                <el-option
                    v-for="schedule in availableScheduleOptions"
                    :key="schedule.scheduleId"
                    :label="getScheduleLabel(schedule)"
                    :value="schedule.scheduleId"
                />
              </el-select>
              <div class="schedule-tips" v-if="availableScheduleOptions.length === 0">
                <el-alert
                    title="暂无可用排班"
                    type="warning"
                    description="当前没有可用的医生排班，请先添加排班或联系管理员"
                    show-icon
                    :closable="false"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="患者姓名" prop="patientName">
              <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="患者性别" prop="patientGender">
              <el-select v-model="form.patientGender" placeholder="请选择性别">
                <el-option label="未知" value="0" />
                <el-option label="男" value="1" />
                <el-option label="女" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="患者年龄" prop="patientAge">
              <el-input v-model="form.patientAge" placeholder="请输入患者年龄" type="number" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="患者电话" prop="patientPhone">
              <el-input v-model="form.patientPhone" placeholder="请输入患者电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="待确认" value="0" />
                <el-option label="已确认" value="1" />
                <el-option label="已完成" value="2" />
                <el-option label="已取消" value="3" />
                <el-option label="已过期" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="症状描述" prop="symptoms">
          <el-input v-model="form.symptoms" type="textarea" placeholder="请输入症状描述" :rows="3" />
        </el-form-item>

        <el-form-item label="取消原因" prop="cancelReason" v-if="form.status === '3'">
          <el-input v-model="form.cancelReason" type="textarea" placeholder="请输入取消原因" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="预约详情" v-model="detailOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentDetail.appointmentNo }}</el-descriptions-item>
        <el-descriptions-item label="挂号费用">{{ currentDetail.appointmentFee || '0.00' }}¥</el-descriptions-item>
        <el-descriptions-item label="就诊人">{{ currentDetail.patientName }}</el-descriptions-item>
        <el-descriptions-item label="患者性别">
          {{ currentDetail.patientGender === '1' ? '男' : currentDetail.patientGender === '2' ? '女' : '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="患者年龄">{{ currentDetail.patientAge }}</el-descriptions-item>
        <el-descriptions-item label="患者电话">{{ currentDetail.patientPhone }}</el-descriptions-item>
        <el-descriptions-item label="医院">{{ currentDetail.hospitalName }}</el-descriptions-item>
        <el-descriptions-item label="科室">{{ currentDetail.departmentName }}</el-descriptions-item>
        <el-descriptions-item label="医生">{{ currentDetail.doctorName }}</el-descriptions-item>
        <el-descriptions-item label="就诊时间">{{ parseTime(currentDetail.visitTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="预约状态">
          <el-tag :type="getStatusType(currentDetail.status)" effect="plain">
            {{ getStatusLabel(currentDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="症状描述" :span="2">{{ currentDetail.symptoms }}</el-descriptions-item>
        <el-descriptions-item label="取消原因" :span="2" v-if="currentDetail.cancelReason">
          {{ currentDetail.cancelReason }}
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ parseTime(currentDetail.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(currentDetail.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AppointmentOrder">
import { listDetail, getDetail, delDetail, addDetail, updateDetail } from "@/api/record/detail"
import { listSchedule } from "@/api/scheduling/schedule.js"
import { listDoctor } from "@/api/medical/doctor"
import { parseTime } from "../../../utils/ruoyi.js";

const { proxy } = getCurrentInstance()

const detailList = ref([])
const scheduleOptions = ref([])
const availableScheduleOptions = ref([])
const doctorOptions = ref([])
const open = ref(false)
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])
const currentDetail = ref({})

// 获取当前登录用户ID
const currentUserId = ref(null)

// 初始化时获取当前用户ID
onMounted(() => {
  getCurrentUserInfo()
})

/** 获取当前用户信息 */
function getCurrentUserInfo() {
  const userInfo = proxy.$cache.session.getJSON("user")
  if (userInfo && userInfo.userId) {
    currentUserId.value = userInfo.userId
    console.log('获取到当前用户ID:', currentUserId.value)
  } else {
    const localUser = localStorage.getItem('user')
    if (localUser) {
      try {
        const userData = JSON.parse(localUser)
        currentUserId.value = userData.userId
        console.log('从localStorage获取到用户ID:', currentUserId.value)
      } catch (e) {
        console.error('解析用户信息失败:', e)
      }
    }
  }

  if (!currentUserId.value) {
    currentUserId.value = 1
    console.warn('使用默认用户ID:', currentUserId.value)
  }
}

/** 生成订单编号 */
function generateAppointmentNo() {
  const timestamp = new Date().getTime()
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `APT${timestamp}${random}`
}

const data = reactive({
  form: {
    hospitalName: null,
    departmentName: null,
    doctorName: null,
    visitTime: null,
    appointmentFee: null,
    userId: null,
    appointmentNo: null // 添加订单编号字段
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appointmentNo: null,
    status: null,
    patientName: null,
    beginVisitTime: null,
    endVisitTime: null,
  },
  rules: {
    scheduleId: [
      { required: true, message: "预约排班不能为空", trigger: "change" }
    ],
    patientName: [
      { required: true, message: "患者姓名不能为空", trigger: "blur" }
    ],
    patientGender: [
      { required: true, message: "患者性别不能为空", trigger: "change" }
    ],
    patientAge: [
      { required: true, message: "患者年龄不能为空", trigger: "blur" }
    ],
    patientPhone: [
      { required: true, message: "患者电话不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "预约状态不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询预约列表 */
function getList() {
  loading.value = true
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginVisitTime = dateRange.value[0]
    queryParams.value.endVisitTime = dateRange.value[1]
  } else {
    queryParams.value.beginVisitTime = null
    queryParams.value.endVisitTime = null
  }

  listDetail(queryParams.value).then(response => {
    detailList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 获取排班选项 */
function getScheduleOptions() {
  listSchedule().then(response => {
    const allSchedules = response.rows || response.data || []
    scheduleOptions.value = allSchedules
    availableScheduleOptions.value = allSchedules.filter(schedule => schedule.status === '0')

    if (availableScheduleOptions.value.length > 0 && !availableScheduleOptions.value[0].hospitalName) {
      enrichScheduleData()
    }
  }).catch(error => {
    console.error('获取排班数据失败:', error)
    scheduleOptions.value = []
    availableScheduleOptions.value = []
  })
}

/** 获取医生列表 */
function getDoctorList() {
  listDoctor({ pageSize: 1000 }).then(response => {
    doctorOptions.value = response.rows || []
  }).catch(error => {
    console.error('获取医生数据失败:', error)
    doctorOptions.value = []
  })
}

/** 丰富排班数据 */
function enrichScheduleData() {
  if (doctorOptions.value.length === 0) {
    getDoctorList()
  }

  availableScheduleOptions.value = availableScheduleOptions.value.map(schedule => {
    if (schedule.doctorId) {
      const doctor = doctorOptions.value.find(d =>
          d.doctorId === schedule.doctorId ||
          d.doctorId?.toString() === schedule.doctorId?.toString()
      )
      if (doctor) {
        return {
          ...schedule,
          hospitalName: doctor.hospitalName,
          departmentName: doctor.departmentName,
          doctorName: doctor.doctorName
        }
      }
    }
    return schedule
  })
}

/** 获取排班显示标签 */
function getScheduleLabel(schedule) {
  if (schedule.hospitalName && schedule.departmentName && schedule.doctorName) {
    return `${schedule.hospitalName} - ${schedule.departmentName} - ${schedule.doctorName} - ${schedule.scheduleDate} ${schedule.startTime}-${schedule.endTime}`
  }
  return `${schedule.doctorName || '医生'} - ${schedule.scheduleDate} ${schedule.startTime}-${schedule.endTime}`
}

/** 排班选择变化 */
function handleScheduleChange(scheduleId) {
  if (scheduleId) {
    const selectedSchedule = availableScheduleOptions.value.find(s => s.scheduleId === scheduleId)
    if (selectedSchedule) {
      form.value.hospitalName = selectedSchedule.hospitalName
      form.value.departmentName = selectedSchedule.departmentName
      form.value.doctorName = selectedSchedule.doctorName
      form.value.visitTime = selectedSchedule.scheduleDate
      form.value.appointmentFee = selectedSchedule.appointmentFee || selectedSchedule.fee || '50.00'
    }
  } else {
    form.value.hospitalName = null
    form.value.departmentName = null
    form.value.doctorName = null
    form.value.visitTime = null
    form.value.appointmentFee = null
  }
}

/** 获取状态标签 */
function getStatusLabel(status) {
  const statusMap = {
    '0': '待确认',
    '1': '已确认',
    '2': '已完成',
    '3': '已取消',
    '4': '已过期'
  }
  return statusMap[status] || '未知'
}

/** 获取状态类型 */
function getStatusType(status) {
  const typeMap = {
    '0': 'warning',
    '1': 'primary',
    '2': 'success',
    '3': 'danger',
    '4': 'info'
  }
  return typeMap[status] || 'info'
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    detailId: null,
    scheduleId: null,
    userId: currentUserId.value,
    patientName: null,
    patientGender: null,
    patientAge: null,
    patientPhone: null,
    symptoms: null,
    appointmentNo: generateAppointmentNo(), // 生成订单编号
    visitTime: null,
    status: null,
    cancelReason: null,
    hospitalName: null,
    departmentName: null,
    doctorName: null,
    appointmentFee: null
  }
  proxy.resetForm("detailRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.detailId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 查看详情操作 */
function handleView(row) {
  currentDetail.value = row
  detailOpen.value = true
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加预约"
  getScheduleOptions()
  getDoctorList()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _detailId = row.detailId || ids.value
  getDetail(_detailId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改预约"
    getScheduleOptions()
    getDoctorList()
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["detailRef"].validate(valid => {
    if (valid) {
      if (!form.value.scheduleId) {
        proxy.$modal.msgError("请选择预约排班")
        return
      }

      const selectedSchedule = availableScheduleOptions.value.find(s => s.scheduleId === form.value.scheduleId)
      if (!selectedSchedule) {
        proxy.$modal.msgError("选择的排班不可用，请重新选择")
        return
      }

      // 确保用户ID不为空
      if (!form.value.userId && currentUserId.value) {
        form.value.userId = currentUserId.value
      }

      // 如果是新增，确保订单编号不为空
      if (!form.value.detailId && !form.value.appointmentNo) {
        form.value.appointmentNo = generateAppointmentNo()
      }

      // 构建提交数据
      const submitData = {
        ...form.value,
        hospitalName: selectedSchedule.hospitalName || form.value.hospitalName,
        departmentName: selectedSchedule.departmentName || form.value.departmentName,
        doctorName: selectedSchedule.doctorName || form.value.doctorName,
        visitTime: selectedSchedule.scheduleDate || form.value.visitTime,
        appointmentFee: selectedSchedule.appointmentFee || selectedSchedule.fee || form.value.appointmentFee || '50.00'
      }

      console.log('提交的数据:', JSON.stringify(submitData, null, 2))

      if (form.value.detailId != null) {
        updateDetail(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(error => {
          console.error('修改失败:', error)
          proxy.$modal.msgError("修改失败")
        })
      } else {
        addDetail(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(error => {
          console.error('新增失败:', error)
          proxy.$modal.msgError("新增失败：" + (error.message || '未知错误'))
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _detailIds = row.detailId || ids.value
  proxy.$modal.confirm('是否确认删除预约编号为"' + _detailIds + '"的数据项？').then(function() {
    return delDetail(_detailIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('record/detail/export', {
    ...queryParams.value
  }, `appointment_order_${new Date().getTime()}.xlsx`)
}

// 初始化
getList()
getDoctorList()
</script>

<style scoped>
.app-container {
  padding: 20px;
}

/* 排班选择器样式优化 */
:deep(.el-select) {
  width: 100%;
}

/* 详情对话框样式 */
:deep(.el-descriptions) {
  margin-top: 10px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

/* 排班提示样式 */
.schedule-tips {
  margin-top: 10px;
}

:deep(.el-alert) {
  padding: 8px 16px;
}
</style>